import { useUserStore } from "@/stores/modules/admin";
import axios, { AxiosRequestConfig, AxiosResponse, AxiosError } from "axios";

// 创建 axios 实例

const httpss = axios.create({
  baseURL: import.meta.env.VITE_API_URL,
  timeout: 5000,
  headers: {
    "Content-Type": "application/json"
  }
});

// 请求拦截器：自动带上 token
httpss.interceptors.request.use(
  config => {
    const authStore = useUserStore();
    const token = authStore.token;
    if (token && config.headers) {
      config.headers["Authorization"] = token;
    }
    console.log("token", token);
    return config;
  },
  error => Promise.reject(error)
);

// 响应拦截器
httpss.interceptors.response.use(
  (response: AxiosResponse) => {
    return response.data;
  },
  (error: AxiosError) => {
    console.error("请求错误：", error);
    return Promise.reject(error);
  }
);

export default httpss;
